<template>
  <div class="app-container">
    <!-- label-position="top" -->
    <el-form v-show="state.showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="queryParams.tagName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="请选择" clearable>
          <el-option
            v-for="dict in combo_tag_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['meal:tag:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAddOrEdit({}, 'add')"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          :disabled="disabled"
          v-hasPermi="['meal:tag:export']"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column label="序号" align="center" width="100">
        <template #default="scope">
          {{ getRowNumber(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column
        label="标签名称"
        align="center"
        prop="tagName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="城市标签"
        align="center"
        prop="cityName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="状态"
        align="center"
        prop="enable"
        :show-overflow-tooltip="true"
        min-width="100"
      >
        <template #default="scope">
          <dict-tag :options="combo_tag_status" :value="scope.row.enable" />
        </template>
      </el-table-column>
      <el-table-column
        label="标签颜色"
        align="center"
        prop="enable"
        :show-overflow-tooltip="true"
        min-width="100"
      >
        <template #default="{ row }">
          <span>{{ getColor(row.color) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作人"
        align="center"
        prop="createOper"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作时间" align="center" prop="updateTime" min-width="100" />
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template #default="scope">
          <el-button
            v-hasPermi="['meal:tag:info']"
            link
            type="primary"
            @click="handleDetails(scope.row, 'view')"
            >查看</el-button
          >
          <el-button
            v-hasPermi="['meal:tag:edit']"
            link
            type="primary"
            @click="handleAddOrEdit(scope.row, 'edit')"
            >编辑</el-button
          >
          <el-button
            v-hasPermi="['meal:tag:dis']"
            link
            type="primary"
            @click="handleTableAction(scope.row)"
            >{{ scope.row.enable === 1 ? '禁用' : '启用' }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />

    <el-dialog
      width="40%"
      v-model="state.dialogVisible"
      :title="state.dialogTitle"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <template v-if="state.operType == 'view'">
        <el-descriptions title="" :column="2">
          <el-descriptions-item label="城市标签:">{{
            cityNameOptions.find((i) => i === state.data.cityName)
          }}</el-descriptions-item>
          <el-descriptions-item label="标签名称:">{{ state.data.tagName }}</el-descriptions-item>

          <el-descriptions-item label="状态管理:">{{
            state.data.enable === 1 ? '启用' : '禁用'
          }}</el-descriptions-item>

          <el-descriptions-item label="操作人:">{{ state.data.createOper }}</el-descriptions-item>
          <el-descriptions-item label="操作时间:">{{ state.data.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="标签颜色:">{{
            getColor(state.data.color)
          }}</el-descriptions-item>
        </el-descriptions>
      </template>

      <template v-else>
        <el-form ref="tagFormRef" :model="form" :rules="rules">
          <el-form-item label="城市标签" prop="cityName">
            <el-select :disabled="editDisabled" v-model="form.cityName" placeholder="请选择">
              <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="tagName">
            <el-input
              style="width: 320px"
              placeholder="请输入标签名称，最多2个字"
              v-model.trim="form.tagName"
              maxlength="2"
            />
          </el-form-item>
          <el-form-item label="标签颜色" prop="color">
            <el-select
              v-model="form.color"
              filterable
              clearable
              style="width: 320px"
              placeholder="请选择"
            >
              <el-option
                v-for="item in combo_tag_color"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <template v-if="state.operType == 'view'">
          <el-button @click="state.dialogVisible = false">关闭</el-button>
        </template>
        <template v-else>
          <div class="dialog-footer">
            <el-button @click="state.dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm" :loading="loadingSubmit">{{
              state.operType == 'add' ? '新增' : '更新'
            }}</el-button>
          </div>
        </template>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GoodsSort">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTagComboList,
  addTagCombo,
  updateTagCombo,
  getTagComboDetail,
  disabletagCombo
} from '@/api/meal/comboTag'
import { reactive, ref } from 'vue'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const queryRef = ref(null)
const { proxy } = getCurrentInstance()
const { combo_tag_status, combo_tag_color } = proxy.useDict('combo_tag_status', 'combo_tag_color')
const editDisabled = computed(() => state.operType === 'edit')

const state = reactive({
  currentId: null,
  dialogTitle: '',
  showSearch: true,
  total: 1,
  loading: false,
  operType: '',
  dialogVisible: false,
  data: {}
})
const rules = {
  tagName: [{ required: true, message: '标签不能为空', trigger: ['blur', 'change'] }],
  color: [{ required: true, message: '颜色不能为空', trigger: 'change' }],
  cityName: [{ required: true, message: '城市不能为空', trigger: ['blur', 'change'] }]
}
const form = ref(null)
const loadingSubmit = ref(false)
const tagFormRef = ref(null)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  tagName: null,
  enable: null,
  cityName: cityNameOptions.value[0]
})
const tableList = ref([])

function handleSearch(confirm) {
  !confirm && queryRef.value.resetFields()
  getList(true)
}
async function getList(refresh) {
  state.loading = true
  if (refresh) queryParams.value.pageNum = 1
  try {
    const res = await getTagComboList(queryParams.value)
    tableList.value = res.rows
    state.total = res.total
  } finally {
    state.loading = false
  }
}

function getRowNumber(index) {
  return (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1
}

/**table Action */
function handleAddOrEdit(row, type) {
  loadingSubmit.value = false
  state.operType = type
  state.dialogTitle = type === 'add' ? '新增标签' : '编辑标签'
  if (state.operType === 'edit') {
    form.value = {
      tagId: row.tagId,
      tagName: row.tagName,
      color: row.color,
      cityName: row.cityName
    }
  } else {
    form.value = {
      tagName: null,
      color: '',
      cityName: queryParams.value.cityName
    }
  }
  state.dialogVisible = true
}
function submitForm() {
  proxy.$refs['tagFormRef'].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true
      if (state.operType === 'add') {
        addTagCombo(form.value).then(
          () => {
            proxy.$modal.msgSuccess('新增成功')
            state.dialogVisible = false
            getList()
          },
          (error) => {
            loadingSubmit.value = false
          }
        )
      } else {
        ElMessageBox.confirm('确认要修改这行数据吗?', '系统提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        })
          .then(() => {
            updateTagCombo(form.value).then(
              () => {
                proxy.$modal.msgSuccess('更新成功')
                state.dialogVisible = false
                getList()
              },
              (error) => {
                loadingSubmit.value = false
              }
            )
          })
          .catch(() => {
            loadingSubmit.value = false
          })
      }
    }
  })
}
function handleDetails(row, type) {
  state.operType = type
  state.dialogTitle = '标签信息'
  getTagComboDetail(row.tagId).then((res) => {
    state.data = res?.data ?? null
    state.dialogVisible = true
    console.log('查看', state.data)
  })
}

function handleTableAction(obj) {
  const tipText = obj.enable === 1 ? '禁用' : '启用' //1启用 0禁用
  ElMessageBox.confirm('确认要 ' + tipText + '"' + obj.tagName + '"' + '吗?', '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  })
    .then(() => {
      disabletagCombo({ tagId: obj.tagId }).then(() => {
        getList()
        ElMessage.success('操作成功')
      })
    })
    .catch(() => {})
}

const getColor = computed(() => {
  return (value) => {
    return combo_tag_color.value.find((item) => item.value === value)?.label
  }
})

const disabled = ref(false)
function handleExport() {
  disabled.value = true
  proxy
    .download(
      '/goods/tagCombo/export',
      { ...queryParams.value },
      `套餐标签列表${new Date().getTime()}.xlsx`
    )
    .then(() => {
      disabled.value = false
    })
    .catch((err) => {
      disabled.value = false
    })
}

/**init */
function init() {
  getList()
}

init()
</script>

<style lang="scss" scoped>
:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
}

:deep(.el-dialog) {
  margin: 0 auto;
  max-height: 100%;
  overflow-y: auto;
}
:deep(.el-dialog:not(.is-fullscreen)) {
  margin-top: 30vh !important;
}
</style>
